package com.example.filedemo;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import java.io.File;
import java.util.Locale;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
import top.zibin.luban.OnRenameListener;

/**
 * Created Date 18/12/16.
 *
 * @author RayChen
 * ClassDescription：文件压缩工具类
 */
public class CompressFileUtils {

    //默认目录
    private String compressDir = "/storage/emulated/0/Android/data/com.aiface.aiface/aiface/图片/";
    private static CompressFileUtils instance = null;

    private CompressFileUtils() {
    }

    public static CompressFileUtils getInstance() {
        if (instance == null) {
            instance = new CompressFileUtils();
        }
        return instance;
    }


    /**
     * @param context     上下文
     * @param fileOldPath 原文件路径
     * @param fileName    文件名称
     * @param storeDir    存储目录
     * @param handler
     * @return 返回压缩后的路径
     */
    public String compressFile(final Context context, final String fileOldPath, final String fileName, String storeDir, Handler handler) {
        DebugLog.d(DebugLog.LOGHsc + " fileOldPath " + fileOldPath + " storeDir " + storeDir+" fileName "+fileName);
        final String[] path = {null};
        Luban.with(context)
                .load(new File(fileOldPath))
                .ignoreBy(500) //超过500k压缩， 不超过返回原路径
                .setTargetDir(storeDir == null ? compressDir : storeDir)
                .setRenameListener(new OnRenameListener() {
                    @Override
                    public String rename(String filePath) {
                        return fileName;
                    }
                })
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        //压缩成功后的文件路径
                        DebugLog.d(DebugLog.LOGHsc + "文件路径："+ file.getAbsolutePath()+"\n"+
                                "文件是否存在 "+file.exists()+"\n"
                                +"文件名 "+file.getName()+"\n"
                                +"是否文件 "+file.isFile());
                        path[0] = file.getPath();
                        Message msg = handler.obtainMessage();
                        Bundle bundle = new Bundle();
                        bundle.putString("path", file.getAbsolutePath());// 将服务器返回的订单号传到Bundle中，，再通过handler传出
                        msg.setData(bundle);
                        msg.arg1 = 0;   // 0为获取验证码成功
                        handler.sendMessage(msg);
                        //显示结果
                        showResult(new File(fileOldPath), file);
                    }


                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                        DebugLog.d(DebugLog.LOGHsc + " e " + e.toString());
                        path[0] = null;

                    }
                }).launch();


        return path[0];
    }


    /**
     * 显示压缩前后的文件大小和宽度对比
     *
     * @param compressFile
     */
    private void showResult(File oldFile, File compressFile) {
        int[] originSize = computeSize(oldFile);
        int[] thumbSize = computeSize(compressFile);
        DebugLog.d(DebugLog.LOGHsc + "showResult: " + String.format(Locale.CHINA, "原图参数：%d*%d, %dk", originSize[0], originSize[1], oldFile.length() >> 10));
        DebugLog.d(DebugLog.LOGHsc + "showResult: " + String.format(Locale.CHINA, "压缩后参数：%d*%d, %dk", thumbSize[0], thumbSize[1], compressFile.length() >> 10));
    }


    /**
     * 获取文件宽高
     *
     * @param srcImg
     * @return
     */
    private int[] computeSize(File srcImg) {
        int[] size = new int[2];

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inSampleSize = 1;

        BitmapFactory.decodeFile(srcImg.getAbsolutePath(), options);
        size[0] = options.outWidth;
        size[1] = options.outHeight;

        return size;
    }
}
